package org.kl.bf.dto;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.kl.bf.utils.BasicConstants;

public class MyConnectionFactory {
	/**
	 * 驱动
	 */
	private String driver;

	/**
	 * 连接字符串
	 */
	private String url;

	/**
	 * 数据库登录用户名称
	 */
	private String username;

	/**
	 * 数据库登录密码
	 */
	private String password;

	/**
	 * 单例模式 获取一个数据库连接工厂
	 */
	private static MyConnectionFactory connFactory = null;

	public static synchronized MyConnectionFactory getConnFactoryInstance(HttpSession session) {
		System.out.println();
		connFactory = new MyConnectionFactory(session);
		return connFactory;
	}

	private MyConnectionFactory(HttpSession session) {
		this.driver = (String) session.getServletContext().getAttribute(BasicConstants.JDBC_DRIVER);
		this.url = (String) session.getServletContext().getAttribute(BasicConstants.JDBC_URL);
		this.username = (String) session.getServletContext().getAttribute(BasicConstants.JDBC_USERNAME);
		this.password = (String) session.getServletContext().getAttribute(BasicConstants.JDBC_PASSWORD);
	}

	/**
	 * 获取连接对象
	 * 
	 * @param db
	 * @return
	 */
	public Connection getConn() {
		Connection conn = null;

		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);
			// 设置不自动提交
			conn.setAutoCommit(false);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return conn;
	}

	/**
	 * 关闭操作
	 * 
	 * @param conn
	 * @param pst
	 * @param rs
	 */
	public static void close(Connection conn, PreparedStatement pst, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pst != null) {
				pst.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取UUID
	 * 
	 * @return
	 */
	public String getUUID() {
		return UUID.randomUUID().toString();
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getDriver() {
		return driver;
	}

	public void setDriver(String driver) {
		this.driver = driver;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

}
